import os, pathlib, shutil
from uuid import UUID

from PyQt5.QtWidgets import QVBoxLayout, QLabel, QDialog, QLineEdit

from data import database, config, get_cover

class CoverEditor(QDialog):
    COMBO_BOX_UUID_ROLE = 1

    def __init__(self, uuid: UUID):
        super().__init__(None)
        self.setWindowTitle('Cover Editor')

        self.uuid: UUID = uuid

        #region
        layout = QVBoxLayout()

        self.uuid_label = QLabel()
        self.uuid_label.setText('Cover UUID')
        layout.addWidget(self.uuid_label)

        self.uuid_view = QLineEdit()
        self.uuid_view.setText(str(self.uuid))
        self.uuid_view.setReadOnly(True)
        layout.addWidget(self.uuid_view)

        self.path_label = QLabel()
        self.path_label.setText('Cover Path')
        layout.addWidget(self.path_label)

        self.path_edit = QLineEdit()
        self.path_edit.setText(database['covers'][self.uuid]['path'])
        self.path_edit.editingFinished.connect(self.path_editing_finished)
        layout.addWidget(self.path_edit)

        self.name_label = QLabel()
        self.name_label.setText('Cover Name')
        layout.addWidget(self.name_label)

        self.name_edit = QLineEdit()
        self.name_edit.setPlaceholderText('Enter cover name here')
        self.name_edit.setText(database['covers'][self.uuid]['name'])
        self.name_edit.editingFinished.connect(self.cover_name_changed)
        layout.addWidget(self.name_edit)

        self.cover_label = QLabel()
        cover_label_pixmap = get_cover(uuid)
        cover_label_pixmap = cover_label_pixmap.scaledToWidth(256)
        self.cover_label.setPixmap(cover_label_pixmap)
        layout.addWidget(self.cover_label)

        self.setLayout(layout)
        #endregion

    def cover_name_changed(self):
        text = self.name_edit.text()
        database['covers'][self.uuid]['name'] = text

    def path_editing_finished(self):
        input_path = pathlib.Path(self.path_edit.text())
        lib_path = pathlib.Path(config['files']['images']['path'] if config['files']['images']['path'] else config['files']['audio']['path'])
        track_path = database['covers'][self.uuid]['path']
        if input_path.is_absolute():
            try:
                input_path = input_path.relative_to(lib_path)
            except ValueError as e:
                print('Error:', ValueError.__name__ + ':', e)
                input_path = pathlib.Path(track_path)
        final_path = str(input_path)
        final_path = final_path.replace('\\', '/')
        for char in '<>:"|?*':
            final_path = final_path.replace(char, '')
        final_path_parts: list[str] = final_path.split('/')
        final_path = ''
        for part in final_path_parts:
            part = part.strip()
            part = part.strip('.')
            final_path += (part + '/')
        final_path = final_path.strip('/')
        self.path_edit.setText(str(input_path))
        if not os.path.exists(pathlib.Path(lib_path, final_path).parent):
            os.makedirs(pathlib.Path(lib_path, final_path).parent)
        shutil.move(
            os.path.join(lib_path, track_path),
            os.path.join(lib_path, final_path)
        )
        database['covers'][self.uuid]['path'] = final_path
        self.path_edit.setText(final_path)
